//
//  Provider.swift
//  memoWidgetExtension
//
//  Created by DaleGuo on 2023/10/11.
//

import CoreData
// import SwiftUI
import WidgetKit

struct Provider: TimelineProvider {


    var viewContext = PersistenceController.shared.viewContext

    func placeholder(in context: Context) -> MemoEntry {

        
        MemoEntry(date: Date(), memo: getMemo() ?? MemoEntity(title: "empty", content: "", updated_time: Date()))
        
    }

    func getSnapshot(in context: Context, completion: @escaping (MemoEntry) -> ()) {

        completion(MemoEntry(date: Date(), memo: getMemo() ?? MemoEntity(title: "empty", content: "", updated_time: Date())))
    }

    func getTimeline(in context: Context, completion: @escaping (Timeline<MemoEntry>) -> ()) {
        print("getTimeLine")
        guard let memo = getMemo() else {
            completion(.init(entries: [], policy: .never))
            return
        }

        let entry = MemoEntry(date: Date(), memo: memo)
        completion(.init(entries: [entry], policy: .never))
    }
}

extension Provider {
    private func getMemo() -> MemoEntity? {
        let request = NSFetchRequest<MemoEntity>(entityName: "MemoEntity")
        do {
            var memos = try viewContext.fetch(request)

            memos = memos.filter { memo in
                memo.del_flag == false
            }

            return memos.first

        } catch {
            return nil
        }
    }
}
